#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"
#include "Common.hpp"

using namespace LogModule;

const std::string gpath = "./";
const std::string gdictname = "dict.txt";
const std::string gsep = ": ";

class Dictionary
{
private:
    bool SplitString(const std::string &line, std::string *key, std::string *value, const std::string &sep)
    {
        auto pos = line.find(sep);
        if(pos == std::string::npos) return false;
        *key = line.substr(0,pos);
        *value = line.substr(pos + sep.size());
        if(key->empty() || value->empty()) return false;
        return true;
    }
    bool LoadDictionary()
    {
        const std::string file = _path + _dictname;
        std::ifstream in(file.c_str());
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file " << file << " error";
            return false;
        }
        std::string line;
        while(getline(in,line))
        {
            std::string key;
            std::string value;
            if(SplitString(line, &key, &value, gsep))
            {
                _dictionary.insert({key,value});
            }
        }
        return true;
    }
    // void Print()
    // {
    //     for(auto e : _dictionary)
    //     {
    //         std::cout << e.first << " " << e.second << std::endl;
    //     }
    // }
public:
    Dictionary(std::string path = gpath,std::string dictname = gdictname):_path(path),_dictname(dictname)
    {
        LoadDictionary();
        //Print();
    }
    std::string Translate(const std::string &word)
    {
        auto iter = _dictionary.find(word);
        if(iter == _dictionary.end()) return "None";
        return iter->second;
    }
    ~Dictionary()
    {}
private:
    std::string _path;
    std::string _dictname;
    std::unordered_map<std::string,std::string> _dictionary;
};

